package com.neuosft.his.dao.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;

import javax.servlet.jsp.jstl.sql.Result;

import com.mysql.cj.exceptions.RSAException;
import com.neuosft.his.dao.BaseDao;
import com.neuosft.his.dao.IDepartmentDao;
import com.neuosft.his.entity.Department;

public class DepartmentDaoImpl extends BaseDao implements IDepartmentDao {

	public Result findAll1() {
		String sql = " select  id, dept_code, dept_name, dept_type, delmark " + "from department d  limit  15 ";
		String[] args = null;
		Result result = query(sql, args);
		return result;
	}

	@Override
	public List findAll() {
		String sql = " select  id, dept_code, dept_name, dept_type, delmark " + "from department d  ";
		String[] args = null;
		Result result = query(sql, args);
		List<Department> lds = r2o(result);
		return lds;
	}

	/**
	 * Result 转换为List
	 * 
	 * @param result
	 * @return
	 */
	private List<Department> r2o(Result result) {
		if (result == null || result.getRowCount() == 0) {
			return null;
		}
		List<Department> lds = new ArrayList<>();
		SortedMap[] sms = result.getRows();
		for (int i = 0; i < sms.length; i++) {
			SortedMap sm = sms[i];
			lds.add(r2o(sm));
		}
		return lds;
	}

	/**
	 * SortedMap 转换为Department对象
	 * 
	 * @param sm
	 * @return
	 */
	private Department r2o(SortedMap sm) {
		if (sm == null || sm.size() == 0) {
			return null;
		}
		Department department = new Department();
		department.setId((int) sm.get("id"));
		department.setDelmark(sm.get("delmark") == null ? -2 : (int) sm.get("delmark"));
		department.setDept_code(sm.get("dept_code") == null ? "" : sm.get("dept_code").toString());
		department.setDept_name(sm.get("dept_name") == null ? "" : sm.get("dept_name").toString());
		department.setDept_type(sm.get("dept_type") == null ? "" : sm.get("dept_type").toString());
		return department;
	}

	@Override
	public Department getById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int modDepartment(Department department) {
		String sql = "  update department   set      dept_code =? ,     dept_name =? ,"
				+ "    dept_type =? , " + " delmark = ?  " + " where id  =   ?  ";
		String[] args = { department.getDept_code(), department.getDept_name(), department.getDept_type(),
				department.getDelmark() + "", department.getId() + "" };
		int i = update(sql, args);
		return i;
	}

	@Override
	public int addDepartment(Department department) {
		String sql = "  insert  into  department (dept_code, dept_name, dept_type) VALUES ( ?, ? , ?    )  ";
		String[] args = { department.getDept_code(), department.getDept_name(), department.getDept_type() };
		int i = insertAndGetId(sql, args);		
		return i ;
	}
	
	public static void main(String[] args) {
		DepartmentDaoImpl daoImpl = new DepartmentDaoImpl();
		daoImpl.addDepartment(new Department(0 , "14","14","14"  ,1));
	}

}
